package com.sdgakj.rest;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.sdgakj.dto.FamilyPersonDTO;
import com.sdgakj.dto.FamilyTreeDTO;
import com.sdgakj.entity.Family;
import com.sdgakj.entity.FamilyPerson;
import com.sdgakj.entity.Person;
import com.sdgakj.service.account.ShiroDbRealm;
import com.sdgakj.service.family.FamilyService;
import com.sdgakj.service.person.PersonService;
import com.sdgakj.utils.DateUtil;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import static org.springframework.data.jpa.domain.AbstractPersistable_.id;

/**
 * 家族树的Restful API的controller
 *
 * @author eiffel
 */
@RestController
@RequestMapping(value = "/api/v1/familytree")
public class FamilyTreeRestController {
    private static Logger logger = LoggerFactory.getLogger(FamilyTreeRestController.class);

    @Autowired
    private FamilyService familyService;

    @Autowired
    private PersonService personService;


    private static final String PAGE_SIZE = "10";

    private static Map<String, String> sortTypes = Maps.newLinkedHashMap();

    /**
     * 显示家族树
     *
     * @return
     */
    @RequestMapping(value = "/showTree", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject showTree(Long userId,Long fId,Long personId) {
        JSONObject result = new JSONObject();
        logger.info("query the family list...");
        Long familyId = 1L;
        if (fId != null) {
            familyId = fId;
        }
        // 通过家族id 查询家族人员集合 遍历集合 查所有人的详细信息
        List<FamilyPerson> list = familyService.getPersonByFfId(familyId);
        List<Person> personList = new ArrayList<>();
        for (FamilyPerson fps:list) {
            Person person=personService.getPersonById(fps.getFpId());
            personList.add(person);
        }
        List<HashMap<String ,Object>>  nodesMapList = new ArrayList<HashMap<String ,Object>>();
		for (Person person : personList) {
			HashMap<String, Object> personMap = new HashMap<String, Object>();
			personMap.put("key", person.getId());
			personMap.put("n", person.getFamilyName() + person.getName());
			personMap.put("s", person.getS());
			if (person.getF()!=null && person.getF()!=0L){
                for(FamilyPerson f:list) {
                    if(f.getFpId()==person.getF()) {
                        personMap.put("f", person.getF());
                    }
                }

			}
			if (person.getM()!=null && person.getM()!=0L){
                for(FamilyPerson f:list) {
                    if( person.getM()==f.getFpId()) {
                        personMap.put("m", person.getM());
                    }
                }
			}
			if (person.getUx()!=null && person.getUx()!=0L){
                for(FamilyPerson f:list) {
                    if(person.getUx()==f.getFpId()) {
                        personMap.put("ux", person.getUx());
                    }
                }
			}
			if (person.getVir()!=null && person.getVir()!=0L){
                for(FamilyPerson f:list) {
                    if(person.getVir()==f.getFpId()) {
                        personMap.put("vir", person.getVir());
                    }
                }
			}
			nodesMapList.add(personMap);
		}
		result.put("nodes",nodesMapList);
        result.put("pId",personId);
        return result;
    }

    /**
     * 显示家族树
     *
     * @return
     */
    @RequestMapping(value = "/newShowTree", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject newShowTree(@RequestParam(value = "userId", required = false) Long userId,
                                  @RequestParam(value = "fId", required = false) Long fId,
                                  @RequestParam(value = "personId",required = false)Long pid) {
        JSONObject jsonResult = new JSONObject();
        FamilyTreeDTO result = new FamilyTreeDTO();
        logger.info("query the family list...");
        //当前家族中的所有person数据
        Long familyId = 1L;
        if (fId != null) {
            familyId = fId;
        }
        // 通过家族id 查询家族人员集合 遍历集合 查所有人的详细信息
        List<FamilyPerson> list = familyService.getPersonByFfId(familyId);
        System.out.println(list.size());
        List<Person> lists=getShowTree(pid);
        List<Person> personList = new ArrayList<>();
 /*       for (Person psss:lists){
            System.out.println(psss.getId());
        }*/
        for(FamilyPerson fps:list){
            for(Person ps:lists){
                if(fps.getFpId().equals(ps.getId())){
                    personList.add(ps);
                }
            }
        }

        //查询这个家族的所有成员
        List<HashMap<String, Object>> nodesMapList = new ArrayList<HashMap<String, Object>>();
        System.out.println(personList.size()+"大小");
        //家族成员就一个人
        if(personList.size()==0) {
                Person person=personService.getPersonById(pid);
                HashMap<String, Object> personMap = new HashMap<String, Object>();
                personMap.put("key", person.getId());
                personMap.put("n", person.getFamilyName() + person.getName());
                personMap.put("s", person.getS());
                for(FamilyPerson fp:list) {
                    if(fp.getFpId()==person.getF()) {
                        personMap.put("f", person.getF());
                    }
                }
                for(FamilyPerson fp:list) {
                    if(fp.getFpId()==person.getM()) {
                        personMap.put("m", person.getM());
                    }
                }
                for(FamilyPerson fp:list) {
                    if(fp.getFpId()==person.getUx()) {
                          personMap.put("ux", person.getUx());
                    }
                }
                for(FamilyPerson fp:list) {
                    if(fp.getFpId()==person.getVir()) {
                        personMap.put("vir", person.getVir());
                    }
                }
                nodesMapList.add(personMap);
        }
        //家族人员不止一个人
        if (personList != null && personList.size()>1) {
            nodesMapList=setTree(personList,list);
        }

        jsonResult.put("nodes", nodesMapList.toArray());
        jsonResult.put("pId",pid);
        //当前家族中的所有关系数�
//        List<Relations> relationsList = relationsService.getRelationsByFamilyID(familyId);
//        result.put("relation", relationsList);
//        result.put("root_id", id);
        return jsonResult;
    }
    private  List<HashMap<String, Object>> setTree( List<Person> personList, List<FamilyPerson> list){
        List<HashMap<String, Object>> nodesMapList = new ArrayList<HashMap<String, Object>>();
        for (Person person : personList) {
            HashMap<String, Object> personMap = new HashMap<String, Object>();
            personMap.put("key", person.getId());
            personMap.put("n", person.getFamilyName() + person.getName());
            personMap.put("s", person.getS());
            if (person.getF() != null && person.getF() != 0L) {
                for(FamilyPerson fp:list) {
                    if(fp.getFpId()==person.getF()) {
                        personMap.put("f", person.getF());
                    }
                }
            }
            if (person.getM() != null && person.getM() != 0L) {
                for(FamilyPerson fp:list) {
                    if(fp.getFpId()==person.getM()) {
                        personMap.put("m", person.getM());
                    }
                }
            }
            if (person.getUx() != null && person.getUx() != 0L) {
                for(FamilyPerson fp:list) {
                    if(fp.getFpId()==person.getUx()) {
                        personMap.put("ux", person.getUx());
                    }
                }
            }
            if (person.getVir() != null && person.getVir() != 0L) {
                for(FamilyPerson fp:list) {
                    if(fp.getFpId()==person.getVir()) {
                        personMap.put("vir", person.getVir());
                    }
                }
            }
            nodesMapList.add(personMap);
        }



        return nodesMapList;
    }


    /**
     * 添加家族成员   在孩子的基础上，世系�
     *
     * @param familyName
     * @param name
     * @param mobile
     * @param description
     * @param company
     * @param education
     * @param school
     * @param borntime
     * @param spouseid
     * @param childid
     * @param familyid
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject createPerson(@RequestParam("familyName") String familyName,
                                   @RequestParam("name") String name,
                                   @RequestParam("mobile") String mobile,
                                   @RequestParam("description") String description,
                                   @RequestParam("company") String company,
                                   @RequestParam("education") String education,
                                   @RequestParam("school") String school,
                                   @RequestParam("borntime") String borntime,
                                   @RequestParam("spouseid") Long spouseid,//配偶id
                                   @RequestParam("childid") Long childid,//子女id
                                   @RequestParam("familyid") Long familyid//所属家族id
    ) {
        JSONObject result = new JSONObject();
        logger.info("create the familyTree person...");
        Person person = new Person();
        //设置表单传过来的基本信息
        person.setFamilyName(familyName);
        person.setName(name);
        person.setMobile(mobile);
        person.setDescription(description);
        person.setCompany(company);
        person.setEducation(education);
        person.setSchool(school);

        //转换日期数据
        Date date = DateUtil.formatStringToDate(borntime, "yyyy-MM-dd HH:mm:ss");
        person.setBornTime(date.toString());

        person.setAlive(1);//默认添加是在�
        // person.setChildNumber(1);//第一次添加只能有1个孩�TODO: 如果是添加兄弟的话，要改动父母的孩子和关系表
/*
        person.setBindUser(0);//默认未关联用户创建指者关联用户
*/
        person.setCreatetime(DateUtil.getDate());
        person.setUpdatetime(DateUtil.getDate());
//        person.setUser(null);//数据库默认是null
        //世系+1
        if (childid != null) {
            Person child = personService.getPersonById(Long.valueOf(childid));
            person.setGeneration(child.getGeneration() + 1);
        }
        //计算年龄
        // TODO: 改成前台动态计算，不能写死
       /*int age = DateUtil.getAge(borntime, "yyyy-MM-dd");
        person.setAge(String.valueOf(age));*/
        //判断是否已婚
        if (spouseid == null) {//没有配偶，未�
            person.setMarry(0);
        } else {//有配�已婚
            person.setMarry(1);//已婚
        }
        //保存person信息，返回该对象的id
        Long saveId = personService.savePerson(person);

        //添加人员关系
        //添加跟孩子的关系
        Family family = new Family(familyid);

        //返回数据
        result.put("nodes", person);
//      result.put("relation", relationsList);// TODO: 2017-04-17
        result.put("root_id", id);

        return result;
    }

    private List<Person> getShowTree(Long pid) {
        Person person = personService.getPersonById(pid);
        Person father = null;
        Person mather = null;
        List<Person> brother = new ArrayList<>();
        List<Person> childrens = new ArrayList<>();
        //需要传到前端的数据
        List<Person> list = new ArrayList<>();
        if (person != null) {
            //判断点击人的性别 M:男，F:女
            if (person.getS().equals("F")) {
                //通过自己丈夫查询
                list.add(person);
                if(person.getVir()!=null && person.getVir()!=0) {
                    person = getHusband(person.getVir());
                }
            }
            if(person.getS().equals("M")){
                list.add(person);
                if(person.getUx()!=null && person.getUx()!=0){
                    Person ux=getWife(person.getUx());
                    list.add(ux);
                }
            }
            //父亲.
            if (person.getF() != null && person.getF()!=0) {
                father = getFather(person.getF());
                if (father != null) {
                    list.add(father);
                    //父亲的父亲，兄弟等
                    Long personId = father.getId();
                    Long fatherId = father.getF();
                    Long matherId = father.getM();
                    if (fatherId != null && fatherId!=0) {
                        //爷爷
                        father = getFather(fatherId);
                        if (father != null ) {
                            list.add(father);
                        }
                        //爷爷的兄弟
                        brother = getBrother(fatherId);
                        if (brother != null) {
                            for (Person p : brother) {
                                //排除自己
                                if (p.getId() != personId) {
                                    list.add(p);
                                }
                            }
                        }
                        //奶奶
                        if(matherId!=null && matherId!=0) {
                            mather = getMather(matherId);
                            if (mather != null) {
                                list.add(mather);
                            }
                        }
                    }
                }
            }
            //母亲.
            if (person.getM() != null && person.getM()!=0) {
                mather = getMather(person.getM());
                if (mather != null) {
                    list.add(mather);
                }
            }
            //兄弟.
            if (person.getF() != null && person.getF()!=0) {
                brother = getBrother(person.getF());
                if (brother != null){
                    for (Person p : brother) {
                        if(p.getId()!=null && p.getId()!=pid) {
                            list.add(p);
                        }
                    }
                }
            }
            //孩子.
            childrens = getChildrens(person.getId());
            if (childrens != null) {
                for (Person p : childrens) {
                    list.add(p);
                    //某一个孩子的儿子:孙子
                    List<Person> grandson = getChildrens(p.getId());
                    if (grandson != null) {
                        for (Person gdn : grandson) {
                            list.add(gdn);
                        }
                    }
                }
            }
        }
        return list;
    }


    //获取父亲
    private Person getFather(Long personId){
        return personService.getPersonById(personId);
    }
    //获取母亲
    private Person getMather(Long personId){
        return personService.getPersonById(personId);
    }
    //获取妻子
    private Person getWife(Long personId){
        return personService.getPersonById(personId);
    }
    //获取丈夫
    private Person getHusband(Long personId){
        return personService.getPersonById(personId);
    }
    //获取兄弟
    private List<Person> getBrother(Long personId){
        return personService.getPersonByFatherId(personId);

    }
    //获取孩子集合。
    private List<Person> getChildrens(Long personId){
        return personService.getPersonByFatherId(personId);
    }


    /*
    * 获取世代数据
    * */
    @RequestMapping("/selectAll")
    @ResponseBody
    public JSONObject getPersonList(Long familyId){
        JSONObject request=new JSONObject();
        List<FamilyPerson> list=familyService.getCountByfid(familyId);//家族成员
        List<FamilyPersonDTO> fpdto = new ArrayList<>();//封装每个世代有多少人
        //世系
        List<Integer> generation=familyService.getPersonGeneration(familyId);
        for (Integer i:generation) {
            List<Person> personlist=new ArrayList<>();//这一世的人
            FamilyPersonDTO fdt=new FamilyPersonDTO();
            for(FamilyPerson fp:list){
                if(fp!=null) {
                    Person p=personService.getPersonById(fp.getFpId());
                    if(fp.getGeneration()!=null) {
                        if (fp.getGeneration() == (long) i) {
                            //说明是一个世系  要添加这一世的人
                            personlist.add(p);
                        }
                    }
                }
            }
            fdt.setPersons(personlist);
            fdt.setGeneration(i);
            fpdto.add(fdt);
        }
        request.put("list",fpdto);
        return request;

    }
}
